# final_audio_fix.py - 最终音频修复检查
import sys
import os


def check_rtasr_file():
    """检查rtasr_client.py文件内容"""
    print("🔍 检查rtasr_client.py文件...")

    rtasr_path = "rtasr_client.py"
    if not os.path.exists(rtasr_path):
        print(f"❌ 文件不存在: {rtasr_path}")
        return False

    try:
        with open(rtasr_path, 'r', encoding='utf-8') as f:
            content = f.read()

        # 检查关键修复是否存在
        checks = [
            ("PyAudio检查", "PYAUDIO_AVAILABLE" in content),
            ("真实录音日志", "开始真实语音录制" in content),
            ("移除测试文本", "这是模拟的语音识别结果" not in content),
            ("连接状态检查", "def is_connected(self)" in content),
            ("错误处理", "_recv_loop" in content)
        ]

        print("📋 文件内容检查:")
        all_good = True
        for check_name, check_result in checks:
            status = "✅" if check_result else "❌"
            print(f"   {status} {check_name}: {'通过' if check_result else '未找到'}")
            if not check_result:
                all_good = False

        return all_good

    except Exception as e:
        print(f"❌ 读取文件失败: {e}")
        return False


def check_config():
    """检查配置文件"""
    print("\n🔍 检查config.py配置...")

    try:
        from config import RTASR_APPID, RTASR_APIKey

        if RTASR_APPID and RTASR_APIKey:
            print(f"✅ RTASR配置正确:")
            print(f"   APPID: {RTASR_APPID}")
            print(f"   APIKey: {RTASR_APIKey[:10]}...{RTASR_APIKey[-5:]}")
            return True
        else:
            print("❌ RTASR配置缺失")
            return False

    except ImportError as e:
        print(f"❌ 配置导入失败: {e}")
        return False


def test_audio_integration():
    """测试音频集成"""
    print("\n🧪 测试音频集成...")

    try:
        # 导入修复后的模块
        from rtasr_client import RtAsrClient, PYAUDIO_AVAILABLE, WEBSOCKET_AVAILABLE
        from config import RTASR_APPID, RTASR_APIKey

        print(f"✅ 模块导入成功")
        print(f"   PyAudio可用: {PYAUDIO_AVAILABLE}")
        print(f"   WebSocket可用: {WEBSOCKET_AVAILABLE}")

        if not PYAUDIO_AVAILABLE:
            print("❌ PyAudio在模块中显示不可用！")
            print("💡 可能的原因：")
            print("   1. 模块加载时PyAudio导入失败")
            print("   2. 需要重启Python环境")
            return False

        # 创建客户端测试
        client = RtAsrClient(RTASR_APPID, RTASR_APIKey)
        print("✅ 语音识别客户端创建成功")

        # 测试连接
        if client.connect():
            print("✅ 语音识别连接测试成功")
            client.stop()
            return True
        else:
            print("❌ 语音识别连接测试失败")
            return False

    except Exception as e:
        print(f"❌ 集成测试失败: {e}")
        print(f"错误详情: {type(e).__name__}: {str(e)}")
        return False


def main():
    """主检查函数"""
    print("🔧 最终音频修复检查")
    print("=" * 50)

    # 1. 检查文件
    if not check_rtasr_file():
        print("\n❌ rtasr_client.py文件检查失败")
        print("💡 请确保使用修复后的文件内容")
        return False

    # 2. 检查配置
    if not check_config():
        print("\n❌ 配置检查失败")
        return False

    # 3. 测试集成
    if not test_audio_integration():
        print("\n❌ 音频集成测试失败")
        return False

    print("\n🎉 所有检查通过！")
    print("💡 现在重启app.py，语音识别应该可以正常工作")
    print("📝 预期日志：'🎙️ 开始真实语音录制，时长: 60秒'")

    return True


if __name__ == "__main__":
    main()